package com.ruicar.afs.cloud.apply.admin.auth.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.ruicar.afs.cloud.apply.admin.manage.entity.SysChannelBasicInfo;
import com.ruicar.afs.cloud.apply.admin.manage.entity.SysPermission;
import com.ruicar.afs.cloud.apply.admin.manage.entity.SysRole;
import com.ruicar.afs.cloud.apply.admin.manage.entity.SysUser;
import com.ruicar.afs.cloud.apply.admin.manage.service.*;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.security.service.SubAuthService;
import com.ruicar.afs.cloud.common.core.security.vo.RoleVo;
import com.ruicar.afs.cloud.common.modules.apply.enums.LockFlagEnum;
import com.ruicar.afs.cloud.common.modules.apply.enums.UserExtInfoKeyEnum;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author: Lee
 * @date: 2020/5/11 19:39
 * @description:
 */
@AllArgsConstructor
@Service(value = "ApplySubAuthServiceImpl")
@Primary
public class ApplySubAuthServiceImpl implements SubAuthService {

    private ApplyUserService applyUserService;
    private ApplyRoleService applyRoleService;
    private ApplyPermissionService applyPermissionService;
    private ApplyDepartmentService applyDepartmentService;
    private ApplyChannelBasicInfoService channelBasicInfoService;

    @Override
    public List<RoleVo> extSubRoles(String userLoginName, String tenantId) {
        //return JSONUtil.parseArray(applyRoleService.findByUserName(userLoginName)).toList(RoleVo.class);
        return Lists.newArrayList();
    }

    @Override
    public List<String> permissions(String userLoginName, String tenantId) {
        SysUser user = applyUserService.getOne(Wrappers.<SysUser>query().lambda().
                eq(SysUser::getUsername, userLoginName).eq(SysUser::getLockFlag, LockFlagEnum.NO.getValue()));
        if (user == null) {
            throw new AfsBaseException(CommonConstants.FAIL, "用户不存在或用户处于锁定状态");
        }
        List<SysPermission> applyPermissions = applyPermissionService.findByUserId(user.getUserId());
        Set<String> permissionVal = new HashSet<>();
        applyPermissions.forEach(e -> permissionVal.add(e.getPermissions()));
        return permissionVal.stream().filter(str -> StringUtils.isNotEmpty(str)).distinct().collect(Collectors.toList());
    }

    @Override
    public List<Long> dataScope(String userLoginName, String tenantId) {

        /* delete by sijun.yu 2020-7-10
        List<SysRole> roles = applyRoleService.findByUserName(userLoginName);
        Integer dataAuth = 0;
        DataTypeEnum typeEnum = DataTypeEnum.own;
        for(SysRole role : roles){
            //通过比较枚举值中的key，来找数据权限最大的那个角色
            Integer dsType = role.getDsType().getKey();
            if(dsType>dataAuth){
                dataAuth = dsType;
                typeEnum = role.getDsType();
            }
        }
        List<String> deptIds = Lists.newArrayList();
        if(DataTypeEnum.ownAndSubordinates == typeEnum){
            deptIds = getDeptIds(userLoginName);
        }
        return deptIds;
        */
        return applyDepartmentService.getDeptIdsDownAndSelf(userLoginName);
    }

    @Override
    public JSONObject getExtUserInfo(String userLoginName, String tenantId) {

        JSONObject obj = new JSONObject();
        SysUser user = applyUserService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, userLoginName).eq(SysUser::getLockFlag, LockFlagEnum.NO.getValue()));
        List<SysRole> roles = applyRoleService.findByUserName(userLoginName);
        obj.put(UserExtInfoKeyEnum.roles.name(), roles);
        // add by sijun.yu 2020-6-29 渠道归属
        if (user.getChannelId() != null) {
            //List<SysDeptAuthRegion> deptAuthRegion = applyDeptAuthRegionService.list(Wrappers.<SysDeptAuthRegion>query().lambda().eq(SysDeptAuthRegion::getDeptId, user.getDeptId()));
            //obj.put(UserExtInfoKeyEnum.deptAuthRegion.name(),deptAuthRegion);
            // 渠道ID
            obj.put(UserExtInfoKeyEnum.channelId.name(), user.getChannelId().toString());
            // 渠道名称
            SysChannelBasicInfo channelInfo = channelBasicInfoService.getOne(Wrappers.<SysChannelBasicInfo>query().lambda().eq(SysChannelBasicInfo::getChannelId, user.getChannelId()));
            if (channelInfo != null) {
                obj.put(UserExtInfoKeyEnum.channelInfo.name(), channelInfo);
            }
            // 部门归属
            obj.put(UserExtInfoKeyEnum.deptIds.name(), applyDepartmentService.getDeptIdsDownAndSelf(userLoginName));
        }
        return obj;
    }

}
